package class1;

import common.ArrayUtils;

/**
 * [3, 5, 6, 3, 4, 5, 2, 6, 9, 0]
 * low                         high
 * i
 * 荷兰国旗问题
 */
public class Code10_QuicketSort {
    static int[] arr = {3, 5, 6, 3, 4, 5, 2, 6, 9, 0};

    public static void main(String[] args) {
        quicketSort(arr, 0, arr.length - 1);
        ArrayUtils.printArr(arr);
    }

    public static void quicketSort(int[] arr, int L, int R) {
        if (L < R) {
            int random = L + (int) (Math.random() * (R - L + 1));
            swap(arr, random, R); //等概率随机选择一个位置
            int[] p = partition(arr, L, R); // 左边界和右边界
            quicketSort(arr, L, p[0] - 1); // < 区
            quicketSort(arr, p[1] + 1, R); // > 区
        }
    }

    public static int[] partition(int[] arr, int L, int R) {
        int less = L - 1;
        int more = R;
        while (L < more) {
            if (arr[L] < arr[R]) {
                swap(arr, ++less, L++);
            } else if (arr[L] > arr[R]) {
                swap(arr, --more, L);
            } else {
                L++;
            }
        }
        swap(arr, more, R);
        return new int[]{less + 1, more};
    }

    public static void swap(int[] arr, int x, int y) {
        int t = arr[x];
        arr[x] = arr[y];
        arr[y] = t;
    }
}
